﻿using ELS.Models;
using System.Data.SQLite;
using System.Data;
using Dapper;

namespace ELS.Services
{
	public class QuestionService
	{

		private readonly string _connectionString = @"Data Source=.\wwwroot\Database\data.db;Version=3";

		public QuestionService()
		{
			
		}

		// 创建问题
		public void AddQuestion(Question question)
		{
			using IDbConnection db = new SQLiteConnection(_connectionString);
			string sqlQuery = "INSERT INTO Question (Title, CurentAnswerIndex, Answer1, Answer2, Answer3, Answer4, Category) VALUES " +
				"(@Title, @CurentAnswerIndex, @Answer1, @Answer2, @Answer3, @Answer4, @Category)";
			db.Execute(sqlQuery, question);
		}

		// 查询所有问题
		public async Task<IEnumerable<Question>> GetAllQuestions()
		{
			using (IDbConnection db = new SQLiteConnection(_connectionString))
			{
				string sqlQuery = "SELECT * FROM Question";
				return await db.QueryAsync<Question>(sqlQuery);
			}
		}

		// 更新问题
		public void UpdateQuestion(Question question)
		{
			using (IDbConnection db = new SQLiteConnection(_connectionString))
			{
				string sqlQuery = "UPDATE Question SET Title = @Title,CurentAnswerIndex = @CurentAnswerIndex,Answer1 = @Answer1,Answer2 = @Answer2,Answer3 = @Answer3,Answer4 = @Answer4,Category = @Category WHERE Id = @Id";
				db.Execute(sqlQuery, question);
			}
		}

		// 删除问题
		public void DeleteQuestion(int id)
		{
			using (IDbConnection db = new SQLiteConnection(_connectionString))
			{
				string sqlQuery = "DELETE FROM Question WHERE Id = @Id";
				db.Execute(sqlQuery, new { Id = id });
			}
		}
	}
}
